package com.mj.listen1._09_Set集合;


import com.mj.listen1._09_Set集合.tree.BinaryTree;
import com.mj.listen1._09_Set集合.tree.RBTree;

import java.util.Comparator;

/**
 * 使用红黑树实现TreeSet集合
 */
public class TreeSet<E> implements Set<E> {

    // 底层使用 RBTree
    private RBTree<E> tree;

    public TreeSet() {
        this(null);
    }

    // TreeSet的元素必须具备可比较性
    public TreeSet(Comparator<E> comparator) {
        tree = new RBTree<>(comparator);
    }

    @Override
    public int size() {
        return tree.size();
    }

    @Override
    public boolean isEmpty() {
        return tree.isEmpty();
    }

    @Override
    public void clear() {
        tree.clear();
    }

    @Override
    public boolean contains(E element) {
        return tree.contains(element);
    }

    @Override
    public void add(E element) {
        // 在RBTree里面对于重复的元素已经实现了覆盖：node.element = newElement;
        tree.add(element);
    }

    @Override
    public void remove(E element) {
        tree.remove(element);
    }

    @Override
    public void traversal(Visitor<E> visitor) {
        tree.inorderTraversal(new BinaryTree.Visitor<E>() {
            @Override
            public boolean visit(E element) {
                // 回调给使用方
                return visitor.visit(element);
            }
        });
    }
}
